﻿using blackhouse.Translator.Business;
using System;
using System.Globalization;
using System.Linq;
using System.Web;

namespace blackhouse.Translator.Web {
    public class WebTranslatorLanguagesManager : TranslatorLanguagesManager {

        #region Properties

        public CultureInfo FromLanguage { get; set; }
        public CultureInfo ToLanguage { get; set; }

        #endregion

        #region Methods

        public void ReadState() {
            //bool redirect = false;
            HttpContext context = HttpContext.Current;
            string from = context.Request["from"];
            string to = context.Request["to"];

            //if (String.IsNullOrEmpty(from) || String.IsNullOrEmpty(to))
            //    redirect = true;

            CultureInfo ciFrom, ciTo;
            this.TryParseCultureInfo(@from, out ciFrom);
            this.TryParseCultureInfo(to, out ciTo);
            //if (!this.TryParseCultureInfo(from, out ciFrom) || !this.TryParseCultureInfo(to, out ciTo))
            //    redirect = true;
            this.FromLanguage = ciFrom;
            this.ToLanguage = ciTo;
            if (this.FromLanguage != null && this.ToLanguage != null) return;
            var cultures = this.GetSupportedLanguages();
            if (cultures.Length >= 2) {
                this.FromLanguage = this.GetDefaultLanguage();
                this.ToLanguage = cultures.First(c => !(c.Equals(this.FromLanguage)));
            } else
                throw new ArgumentException("Do poprawnego działania modułu wymagane są conajmniej dwa języki");
        }

        private void TryParseCultureInfo(string value, out CultureInfo cultureInfo) {
            if (String.IsNullOrEmpty(value)) {
                cultureInfo = null;
                return;
            }
            cultureInfo = CultureInfo.GetCultures(CultureTypes.AllCultures).FirstOrDefault(ci => ci.Name.Equals(value, StringComparison.InvariantCultureIgnoreCase));
        }

        #endregion

    }
}